import type { Server, WebSocket } from 'ws';
const useWs = (ws: Server) => {
  const clients: Array<WebSocket> = [];
  const subscribeClients: Array<WebSocket> = [];
  const dispatchClients: Array<WebSocket> = [];
  ws.on('connection', (socket, res) => {
    // console.log(res);
    clients.push(socket);
    if (res.url?.includes('subscribe')) subscribeClients.push(socket);
    if (res.url?.includes('dispatch')) dispatchClients.push(socket);
    socket.on('message', (msg) => {
      if (typeof msg === 'string') {
        subscribeClients.forEach((client) => {
          client.send(msg);
        });
      } else if (msg instanceof Buffer) {
        console.log(msg.toString());
        subscribeClients.forEach((client) => {
          client.send(msg.toString());
        });
      }
      if (dispatchClients.includes(socket)) socket.send(`发送成功${Date.now()}`);
    });

    socket.on('close', () => {
      clients.splice(clients.indexOf(socket), 1);
      subscribeClients.splice(subscribeClients.indexOf(socket), 1);
    });
  });
};

export default useWs;
